package com.plat.api.api.action;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.plat.api.anonation.NoToken;
import com.plat.api.anonation.Token;
import com.plat.api.api.action.common.BuildOrderParam;
import com.plat.api.api.action.common.CommonMethod;
import com.plat.api.common.OrderType;
import com.plat.api.common.RespCode;
import com.plat.api.dao.api.*;
import com.plat.api.entity.api.*;
import com.plat.api.exception.PlatException;
import com.plat.api.mapper.PlatSubLiveMapper;
import com.plat.api.util.SnowflakeIdWorker;
import com.plat.api.util.YmalPropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

import static com.plat.api.common.OrderType.WECHAT_PAY;

/**
 * Created with IntelliJ IDEA.
 * User: shish
 * Date: 2020/7/11
 * Time: 13:28
 * Description: 直播相关接口
 */
@Slf4j
@Service
@Token
public class PlatLiveAction {
    @Autowired
    private WxPayService wxService;
    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private PlatWechatLiveRoomDao platWechatLiveRoomDao;
    @Autowired
    private PlatSubLiveMapper platSubLiveMapper;
    @Autowired
    private PlatOrderDao platOrderDao;
    @Autowired
    private PlatOrderDetailDao platOrderDetailDao;

    /**
     * 开房间直播
     */
    public JSONObject publish(JSONObject jsonObject) throws WxErrorException {
        String accessToken = wxMaService.getAccessToken();
        JSONObject param = jsonObject.getJSONObject("body");
        JSONObject head = jsonObject.getJSONObject("head");
        TokenEntity tokenEntity = tokenDao.getSQLManager().lambdaQuery(TokenEntity.class).andEq("token", head.getString("token")).single();
        String name = param.getString("name");
        Date startTime = param.getDate("startTime");
        Date endTime = param.getDate("endTime");
        String anchorName = param.getString("anchorName");
        String anchorWechat = param.getString("anchorWechat");
        String coverImgUrl = param.getString("coverImgUrl");
        String shareImgUrl = param.getString("shareImgUrl");
        Integer type = param.getInteger("type");
        Integer screenType = param.getInteger("screenType");
        Integer closeLike = param.getInteger("closeLike");
        Integer closeGoods = param.getInteger("closeGoods");
        Integer closeComment = param.getInteger("closeComment");
        String detail = param.getString("detail");
        Integer isFree = param.getInteger("isFree");
        Double price = param.getDouble("price");
        File file = FileUtil.file(YmalPropertiesUtil.getValue("sys.upload.url").toString());
        File file1 = FileUtil.file(YmalPropertiesUtil.getValue("sys.upload.url").toString());
        long size = HttpUtil.downloadFile(coverImgUrl, file);
        File files = file;
        WxMediaUploadResult coverImg = wxMaService.getMediaService().uploadMedia("image", new File(YmalPropertiesUtil.getValue("sys.upload.url").toString() + "/" + file.getAbsoluteFile().list()[2]));
        long size1 = HttpUtil.downloadFile(coverImgUrl, file1);
        File file11 = file1;
        WxMediaUploadResult shareImg = wxMaService.getMediaService().uploadMedia("image", new File(YmalPropertiesUtil.getValue("sys.upload.url").toString() + "/" + file1.getAbsoluteFile().list()[2]));
        JSONObject jsonMap = new JSONObject();
        Long st = startTime.getTime() / 1000;
        Long et = endTime.getTime() / 1000;
        jsonMap.put("name", name);
        jsonMap.put("coverImg", coverImg.getMediaId());
        jsonMap.put("startTime", st);
        jsonMap.put("endTime", et);
        jsonMap.put("anchorName", anchorName);
        jsonMap.put("anchorWechat", anchorWechat);
        jsonMap.put("shareImg", shareImg.getMediaId());
        jsonMap.put("type", type);
        jsonMap.put("screenType", screenType);
        jsonMap.put("closeLike", closeLike);
        jsonMap.put("closeGoods", closeGoods);
        jsonMap.put("closeComment", closeComment);
        JSONObject json = new JSONObject();
        String js = jsonMap.toJSONString();
        try {
            String result = HttpUtil.post("https://api.weixin.qq.com/wxaapi/broadcast/room/create?access_token=" + accessToken, js);
            JSONObject res = JSONObject.parseObject(result);
            if (res.getLong("roomId") != null) {
                PlatWechatLiveRoomEntity entity = new PlatWechatLiveRoomEntity();
                entity.setName(name);
                entity.setCoverImg(coverImg.getMediaId());
                entity.setStartTime(startTime);
                entity.setEndTime(DateUtil.format(endTime, "yyyy-MM-dd hh:mm:ss"));
                entity.setAnchorName(anchorName);
                entity.setAnchorWechat(anchorWechat);
                entity.setShareImg(shareImg.getMediaId());
                entity.setType(type);
                entity.setScreenType(screenType);
                entity.setCloseLike(closeComment);
                entity.setCloseGoods(closeGoods);
                entity.setCloseComment(closeComment);
                entity.setPassword("");
                entity.setCoverImgUrl(coverImgUrl);
                entity.setShareImgUrl(shareImgUrl);
                entity.setDetail(detail);
                entity.setIsTop(0);
                entity.setDetail(detail);
                entity.setImageUrls("");
                entity.setIsCheck(0);
                entity.setRoomId(res.getLong("roomId"));
                entity.setIsOffonline(1);
                entity.setIsFree(isFree);
                entity.setPrice(price);
                entity.setPoster("");
                entity.setMediaUrl("");
                entity.setCreateUser(tokenEntity.getUserId());
                platWechatLiveRoomDao.insert(entity);
                json.put("object", entity);
            } else {
                Map<String, Object> descMsg = getDesc(res);
                throw new PlatException(descMsg.get("code").toString(), descMsg.get("msg").toString(),descMsg.get("msg").toString());
            }
        } catch (PlatException e) {
            e.printStackTrace();
            log.info("[开通房间直播失败，请联系管理员]");
            throw new PlatException(e.getCode(), e.getDesc(),e.getDesc());
        }
        return json;
    }

    private Map<String, Object> getDesc(JSONObject res) {
        Map<String, Object> result = new HashMap<>();
        String msg;
        if (res.getString("errcode").equals("-1")) {
            msg = "微信系统错误";
            result.put("code", -1);
            result.put("msg", msg);
        }
        if (res.getString("errcode").equals("1")) {
            msg = "未创建直播间";
            result.put("code", 1);
            result.put("msg", msg);
        }
        if (res.getString("errcode").equals("300029")) {
            msg = "主播昵称违规";
            result.put("code", 300029);
            result.put("msg", msg);
        }
        if (res.getString("errcode").equals("300028")) {
            msg = "房间名称违规";
            result.put("code", 300028);
            result.put("msg", msg);
        }
        if (res.getString("errcode").equals("300001")) {
            msg = "禁止创建/更新商品 或 禁止编辑&更新房间";
            result.put("code", 300001);
            result.put("msg", msg);
        }
        if (res.getString("errcode").equals("300002")) {
            msg = "名称长度不符合规则";
            result.put("code", 300002);
            result.put("msg", msg);
        }
        if (res.getString("errcode").equals("300006")) {
            msg = "图片上传失败";
            result.put("code", 300006);
            result.put("msg", msg);
        }
        if (res.getString("errcode").equals("300030")) {
            msg = "主播微信号不合法";
            result.put("code", 300030);
            result.put("msg", msg);
        }
        if (res.getString("errcode").equals("300031")) {
            msg = "直播间封面图不合规";
            result.put("code", 300031);
            result.put("msg", msg);
        }
        if (res.getString("errcode").equals("300035")) {
            msg = "主播微信号不存在";
            result.put("code", 300035);
            result.put("msg", msg);
        }
        if (res.getString("errcode").equals("300036")) {
            msg = "主播微信号未实名认证";
            result.put("code", 300036);
        } else {
            msg = "其他问题，请联系管理";
            result.put("code", 300037);
        }
        result.put("msg", msg);
        return result;
    }

    @NoToken
    public JSONObject getLive(JSONObject jsonObject) {
        JSONObject param = jsonObject.getJSONObject("body");
        Integer id = param.getInteger("id");
        LambdaQuery<PlatWechatLiveRoomEntity> query = platWechatLiveRoomDao.getSQLManager().lambdaQuery(PlatWechatLiveRoomEntity.class);
        List<PlatWechatLiveRoomEntity> list = query.andEq("id", id).page(1, 1).getList();
        JSONObject json = new JSONObject();
        json.put("object", list.get(0));
        return json;
    }

    @NoToken
    public JSONObject getLiveList(JSONObject jsonObject) throws WxErrorException {
        List<PlatWechatLiveRoomEntity> list1 = getPlatWechatLiveRoom(jsonObject, false);
        JSONObject head = jsonObject.getJSONObject("head");
        TokenEntity tokenEntity = tokenDao.getSQLManager().lambdaQuery(TokenEntity.class).andEq("token", head.getString("token")).single();
        UserEntity userEntity = userDao.unique(tokenEntity.getUserId());
        JSONObject json = new JSONObject();

        for (PlatWechatLiveRoomEntity roomEntity : list1) {
            QueryWrapper<PlatLiveSubEntity> qw = new QueryWrapper<>();
            qw.eq("live_id", roomEntity.getId());
            qw.eq("user_id", userEntity.getId());
            PlatLiveSubEntity platLiveSubEntity = platSubLiveMapper.selectOne(qw);
            if (platLiveSubEntity != null) {
                roomEntity.setIsSub(1);
            } else {
                roomEntity.setIsSub(0);
            }
            QueryWrapper<PlatLiveSubEntity> qw_1 = new QueryWrapper<>();
            qw_1.eq("live_id", roomEntity.getId());
            Integer count = platSubLiveMapper.selectCount(qw_1);
            roomEntity.setSubNum(count);
            UserEntity user = userDao.createLambdaQuery().andEq("id", roomEntity.getCreateUser()).single();
            roomEntity.setUser(user);
        }
        //正在直播
        List<PlatWechatLiveRoomEntity> roomEntityList = new ArrayList<>();
        //近期直播
        List<PlatWechatLiveRoomEntity> list = new ArrayList<>();
        for (PlatWechatLiveRoomEntity roomEntity : list1) {
            if (roomEntity.getLiveStatusName().equals("直播中")) {
                roomEntityList.add(roomEntity);
            } else {
                list.add(roomEntity);
            }
        }
        list1.clear();
        //电影一直播的类型
        json.put("list", JSON.toJSONString(list, SerializerFeature.DisableCircularReferenceDetect));
        json.put("liveList", JSON.toJSONString(roomEntityList, SerializerFeature.DisableCircularReferenceDetect));
        json.put("object", userEntity);
        return json;
    }

    public List<PlatWechatLiveRoomEntity> getPlatWechatLiveRoom(JSONObject jsonObject, boolean isRand) throws WxErrorException {
        String accessToken = wxMaService.getAccessToken();
        JSONObject param = jsonObject.getJSONObject("body");
        Integer page = param.getInteger("page");
        Integer pageSize = param.getInteger("pageSize");
        LambdaQuery<PlatWechatLiveRoomEntity> query = platWechatLiveRoomDao.createLambdaQuery();
        List<PlatWechatLiveRoomEntity> list = null;
        if (isRand) {
            list = query.orderBy(" RAND() ").page(1, 1).getList();
        } else {
            list = query.orderBy("id desc").page(page, pageSize).getList();
        }
        JSONArray res = new JSONArray();
        try {
            JSONObject map = new JSONObject();
            map.put("start", page - 1);
            map.put("limit", pageSize);
            String result = HttpUtil.post("https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=" + accessToken, map.toJSONString());
            res = JSONObject.parseObject(result).getJSONArray("room_info");
        } catch (Exception e) {
            log.info("[获取房间号码失败]");
        }
        List<PlatWechatLiveRoomEntity> list1 = new ArrayList<>();
        for (PlatWechatLiveRoomEntity entity : list) {
            if (res != null) {
                for (Object obj : res) {
                    JSONObject jsobj = (JSONObject) obj;
                    if (String.valueOf(entity.getRoomId()) != null) {
                        if (entity.getRoomId() == jsobj.getLong("roomid")) {
                            Integer liveStatus = jsobj.getInteger("live_status");
                            String liveStatusName = "直播状态";
                            entity.setLiveStatus(liveStatus);
                            if (liveStatus == 101) {
                                liveStatusName = "直播中";
                            }
                            if (liveStatus == 102) {
                                liveStatusName = "未开始";
                            }
                            if (liveStatus == 103) {
                                liveStatusName = "已结束";
                            }
                            if (liveStatus == 104) {
                                liveStatusName = "禁播";
                            }
                            if (liveStatus == 105) {
                                liveStatusName = "暂停";
                            }
                            if (liveStatus == 106) {
                                liveStatusName = "异常";
                            }
                            if (liveStatus == 107) {
                                liveStatusName = "已过期";
                            }
                            entity.setStart_Time(DateUtil.format(entity.getStartTime(), "MM-dd hh:mm"));
                            entity.setEnd_Time(entity.getEndTime());
                            entity.setLiveStatusName(liveStatusName);
                            entity.setLiveStatus(liveStatus);
                            platWechatLiveRoomDao.updateById(entity);
                            if (liveStatus == 101 || liveStatus == 102 || liveStatus == 103 || liveStatus == 105) {
                                list1.add(entity);
                            }
                        }
                    }
                }
            }
        }
        return list1;
    }

    public JSONObject subLive(JSONObject jsonObject) throws WxPayException {
        JSONObject param = jsonObject.getJSONObject("body");
        JSONObject head = jsonObject.getJSONObject("head");
        TokenEntity tokenEntity = tokenDao.getSQLManager().lambdaQuery(TokenEntity.class).andEq("token", head.getString("token")).single();
        UserEntity userEntity = userDao.unique(tokenEntity.getUserId());
        QueryWrapper<PlatLiveSubEntity> qw = new QueryWrapper<>();
        qw.eq("live_id", param.getInteger("id"));
        qw.eq("user_id", tokenEntity.getUserId());
        PlatLiveSubEntity platLiveSubEntity = platSubLiveMapper.selectOne(qw);
        JSONObject result = new JSONObject();
        LambdaQuery<PlatWechatLiveRoomEntity> query = platWechatLiveRoomDao.getSQLManager().lambdaQuery(PlatWechatLiveRoomEntity.class).andEq("id", param.getInteger("id"));
        PlatWechatLiveRoomEntity roomEntity = query.single();
        if (platLiveSubEntity == null) {
            //发起订阅
            if (roomEntity.getPrice() != 0D) {
                String outTradeNo = SnowflakeIdWorker.getId();
                Object json = sub(roomEntity, userEntity, outTradeNo);
                PlatOrderEntity order = new PlatOrderEntity();
                BuildOrderParam buildOrderParam = new BuildOrderParam();
                buildOrderParam.setGoodsName(roomEntity.getName());
                buildOrderParam.setGoodsDetail(roomEntity.getDetail());
                buildOrderParam.setOrder(order);
                buildOrderParam.setPlatOrderDao(platOrderDao);
                buildOrderParam.setPlatOrderDetailDao(platOrderDetailDao);
                buildOrderParam.setUserEntity(userEntity);
                buildOrderParam.setOutTradeNo(outTradeNo);
                buildOrderParam.setPrice(roomEntity.getPrice());
                buildOrderParam.setGoodsId(roomEntity.getId());
                buildOrderParam.setOrderType(OrderType.LIVE);
                buildOrderParam.setExpressFee(new BigDecimal(0));
                CommonMethod.createOrder(buildOrderParam);
                result.put("pay", json);
                result.put("isSub", 0);
            } else {
                PlatLiveSubEntity subEntity = new PlatLiveSubEntity();
                subEntity.setLiveId(roomEntity.getId());
                subEntity.setUserId(userEntity.getId());
                subEntity.setStartTime(roomEntity.getStartTime());
                subEntity.setPayStatus(1);
                subEntity.setCreateTime(new Date());
                platSubLiveMapper.insert(subEntity);
                result.put("pay", null);
                result.put("isSub", 1);
            }
        } else {
            result.put("isSub", 1);
        }
        result.put("sub", query.single());
        return result;
    }

    public Object sub(PlatWechatLiveRoomEntity roomEntity, UserEntity userEntity, String outTradeNo) throws WxPayException {
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
        request.setOpenid(userEntity.getOpenId());
        String payBody = StringUtils.substring(roomEntity.getDetail(), 0, 25) + "...";
        request.setBody(payBody);
        request.setOutTradeNo(outTradeNo);
        Double p = roomEntity.getPrice() * 100;
        request.setTotalFee(p.intValue());
        request.setSpbillCreateIp("0.0.0.0");
        request.setNotifyUrl(YmalPropertiesUtil.getValue("wxpay.sub-notify-url").toString());
        request.setTradeType("JSAPI");
        WxPayMpOrderResult wxPayMpOrderResult = wxService.createOrder(request);
        return wxPayMpOrderResult;
    }

}
